package com.gxa.luckin.sso.controller;

import com.gxa.luckin.core.exception.BusinessException;
import com.gxa.luckin.core.exception.MessageCode;
import com.gxa.luckin.core.pojo.User;
import com.gxa.luckin.core.utils.JsonResult;
import com.gxa.luckin.sso.service.SsoService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Map;

@RestController
@CrossOrigin
@RequestMapping("/user")
public class SsoController {
    @Resource
    SsoService ssoService;
    @PostMapping("/login")
    public JsonResult login(@RequestParam String phone, @RequestParam String code) throws BusinessException {
        if(!phone.matches("^[1](([3][0-9])|([4][5,7,9])|([5][0-9])|([6][6])|([7][3,5,6,7,8])|([8][0-9])|([9][8,9]))[0-9]{8}$")){
            throw new BusinessException(MessageCode.PHONE_ERROR);
        }
        Map<String, String> login = ssoService.login(phone, code);

        JsonResult jsonResult = new JsonResult();
        jsonResult.setCode("1");
        jsonResult.setData(login);

        return jsonResult;
    }


    @PostMapping("/validateToken")
    public JsonResult validateToken(@RequestParam String token) throws BusinessException {
        User user = ssoService.validateToken(token);

        JsonResult jsonResult = new JsonResult();
        jsonResult.setCode("1");
        jsonResult.setData(user);
        return jsonResult;
    }

}
